﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using FuturamaKassa.Commands.ReceiveCommands;
using FuturamaKassa.Objects;
using FuturamaKassa.Database;
using FuturamaKassaWithGUI;

namespace FuturamaKassa {

    class COMHandler {
        private SerialPort serialPort;
        private COMListener listener;
        private COMWriter writer;

        public COMHandler() {

            //Setting up the Serial Port
            serialPort = new SerialPort();

            serialPort.PortName = "COM4";
            serialPort.BaudRate = 9600;
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;
            serialPort.StopBits = StopBits.One;
            serialPort.Handshake = Handshake.None;

            serialPort.ReadTimeout = 500;
            serialPort.WriteTimeout = 500;

            serialPort.Open();

            //Setting up the listener and writer for the Serial Port

            listener = new COMListener(this, serialPort);
            writer = new COMWriter(this, serialPort);
        }

        public void closePort() {
            serialPort.Close();
        }

        /**
         * A function that handles the commands gotten from the Listener
         * 
         * String: command - number of the command
         * List<byte>: response - an array with the complete response
         */
        public void execute(string command, List<byte> response) {

            ReceiveCommand commandClass;

            switch (command) {
                case "1001":
                    commandClass = new VersionNumber();
                    commandClass.Execute(response);
                    break;
                case "6C20":
                    commandClass = new CreateInventory();
                    commandClass.Execute(response);
                    break;
                case "6C21":
                    commandClass = new GetInventory();
                    commandClass.Execute(response);
                    break;
                default:
                    Logger.Instance.writeLog("Command Unknown");
                    break;
            }
        }
    }
}
